package cn.phub.basic.util;

import cn.phub.basic.jwt.JwtUtils;
import cn.phub.basic.jwt.Payload;
import cn.phub.basic.jwt.RsaUtils;
import cn.phub.basic.jwt.UserInfo;
import cn.phub.user.domain.Logininfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 登录上下文
 */
public class LoginContext {

    private static final String jwtRsaPublic = "hrm_auth_rsa.pub";//公钥的文件名字

    /**
     * 获取当前登录人
     * @return
     */
    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            //判断有没有携带token
            String token = request.getHeader("U-TOKEN");//变成了jwt串
            //根据token--解密token得到登录人相关的所有信息
            PublicKey publicKey = RsaUtils
                    .getPublicKey((FileCopyUtils
                            .copyToByteArray(Logininfo.class.getClassLoader().getResourceAsStream(jwtRsaPublic))));
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            return userInfo.getUser();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
